package life.kenny.community.advice;

import com.alibaba.fastjson.JSON;
import life.kenny.community.dto.ResultDTO;
import life.kenny.community.exception.CustomizeErrorCode;
import life.kenny.community.exception.CustomizeException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.RequestToViewNameTranslator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Jay
 * @date 2021/11/12 9:09 上午
 */
@ControllerAdvice
public class CustomizeExceptionHandler {

        @ExceptionHandler(Exception.class)
        ModelAndView handleControllerException(
                HttpServletRequest request,
                Throwable ex,
                HttpServletResponse response,
                Model model) {


            String contentType = request.getContentType();

            if ("application/josn".equals(contentType)) {
                ResultDTO resultDTO;
                //返回json
                if (ex instanceof CustomizeException) {
                    resultDTO = ResultDTO.errorOf((CustomizeException) ex);
                } else {
                    resultDTO = ResultDTO.errorOf(CustomizeErrorCode.SYS_ERROR);
                }
                try {
                    response.setContentType("application/json");
                    response.setStatus(200);
                    response.setCharacterEncoding("utf-8");
                    PrintWriter writer = response.getWriter();
                    writer.write(JSON.toJSONString(resultDTO));
                    writer.close();
                } catch (IOException e) {
                }
                return null;
            } else {
                //错误页面的跳转
                if (ex instanceof CustomizeException) {
                    model.addAttribute("message", ex.getMessage());
                } else {
                    model.addAttribute("message", CustomizeErrorCode.SYS_ERROR.getMessage());
                }
            }
            return new ModelAndView("error");
        }




}
